<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_qqailab/model')->方法名();
*/
namespace jy_qqailab;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function getReqSign($params=array())
	{
		$basic=$this->plugin_setting('basic');
		if(!$basic['app_id'] || !$basic['app_key']){
			exi('签名失败，腾讯语音合成接口的基本参数未填写','error');
		}
		$new=array(
			'app_id'     => $basic['app_id'],
			'time_stamp' => TIMESTAMP,
			'nonce_str'  => random(10),
			'key1'       => 'jy_qqailab',
			'key2'       => 'jinyun',
			'sign'       => '',
		);
		$params=array_merge($params,$new);
		ksort($params);
		$str = '';
		foreach ($params as $key => $value)
		{
			if ($value !== '')
			{
				$str .= $key . '=' . urlencode($value) . '&';
			}
		}
		$str .= 'app_key=' . $basic['app_key'];
		//print_r($str);exit;
		$params['sign'] = strtoupper(md5($str));
		return $params;
	}
	public function toapi($post=array())
	{	
		if(!$post['text']){
			exi('请输入要合成的文字','error');
		}
		$params['text']=$post['text'];
		$audiotype=$basic['list'][$post['audiotype']];
		$params['speaker']=$audiotype['speaker']?:'1';
		$params['format']=$audiotype['format']?:'2';
		$params['volume']=$audiotype['volume']?:'0';
		$params['speed']=$audiotype['speed']?:'100';
		$params['aht']=$audiotype['aht']?:'0';
		$params['apc']=$audiotype['apc']?:'58';
		$params=$this->getReqSign($params);
		//print_r($params);exit;
		$url = 'https://api.ai.qq.com/fcgi-bin/aai/aai_tts';
		$result=cfc('http')->ihttp_post($url,$params);
		$content=json_decode($result['content'],true);
		if($content['ret']){
			$msg=$this->error_code($content['ret']);
			exi('错误码：'.$content['ret'].'-'.$msg,'error');
		}
		return $content;
	}
	//错误码
	public function error_code($code, $errmsg = '未知错误') {//获取错误详情
		global $_AR;
		$errors = array(
			'9' => 'qps超过限制，用户认证升级或者降低调用频率',
			'4096' => '参数非法，请检查请求参数是否符合要求',
			'12289' => '请检查app_id是否有效的应用标识（AppId）',
			'16388' => '签名错误，请检查AppId跟Appkey是否匹配！',
			'16389' => '缺失API权限',
		);
		$code = strval($code);
		if($errors[$code]) {
			return $errors[$code];
		} else {
			return $errmsg;
		}
	}
}
?>